package com.jzo2o.customer.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jzo2o.api.customer.dto.response.AddressBookResDTO;
import com.jzo2o.api.publics.MapApi;
import com.jzo2o.common.expcetions.ForbiddenOperationException;
import com.jzo2o.common.model.PageResult;
import com.jzo2o.common.utils.BeanUtils;
import com.jzo2o.common.utils.CollUtils;
import com.jzo2o.common.utils.NumberUtils;
import com.jzo2o.customer.mapper.AddressBookMapper;
import com.jzo2o.customer.model.domain.AddressBook;
import com.jzo2o.customer.model.dto.request.AddressBookPageQueryReqDTO;
import com.jzo2o.customer.model.dto.request.AddressBookUpsertReqDTO;
import com.jzo2o.customer.service.IAddressBookService;
import com.jzo2o.mvc.utils.UserContext;
import com.jzo2o.mysql.utils.PageHelperUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 地址薄 服务实现类
 * </p>
 *
 * @author itcast
 * @since 2023-07-06
 */
@Service
public class AddressBookServiceImpl extends ServiceImpl<AddressBookMapper, AddressBook> implements IAddressBookService {

    @Resource
    private MapApi mapApi;
    @Override
    public List<AddressBookResDTO> getByUserIdAndCity(Long userId, String city) {
        List<AddressBook> addressBooks = lambdaQuery()
                .eq(AddressBook::getUserId, userId)
                .eq(AddressBook::getCity, city)
                .list();
        if(CollUtils.isEmpty(addressBooks)) {
            return new ArrayList<>();
        }
        return BeanUtils.copyToList(addressBooks, AddressBookResDTO.class);
    }

    /**
     * 新增地址
     * @param dto
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void add(AddressBookUpsertReqDTO dto) {
        Long userId = UserContext.currentUserId();
        if (ObjectUtil.isNull(userId)) {
            throw new ForbiddenOperationException("请登录后再操作");
        }
        // 获取用户地址的数量
        Integer count = this.lambdaQuery().eq(AddressBook::getUserId, userId).count();
        // 如果是第一次新增地址，直接新增地址
        if (count == 0) {
            addAddressBook(dto, userId);
            return;
        }

        // 默认地址一个人只有一个，如果设置新地址为默认地址需要取消旧的默认地址
        if (dto.getIsDefault() == 1) {
            boolean update = this.lambdaUpdate()
                    .set(AddressBook::getIsDefault, 0)
                    .eq(AddressBook::getUserId, userId)
                    .eq(AddressBook::getIsDefault, 1)
                    .update();
            if (!update) {
                throw new ForbiddenOperationException("新增地址失败");
            }
        }
        addAddressBook(dto, userId);
    }
    public void addAddressBook(AddressBookUpsertReqDTO dto, Long userId) {
        AddressBook addressBook = BeanUtil.copyProperties(dto, AddressBook.class);
        addressBook.setUserId(userId);
        // 获取经纬度
        String location = mapApi.getLocationByAddress(dto.getAddress()).getLocation();
        addressBook.setLon(NumberUtils.parseDouble(location.split(",")[0]));
        addressBook.setLat(NumberUtils.parseDouble(location.split(",")[1]));
        boolean flag = this.save(addressBook);
        if (!flag) {
            throw new ForbiddenOperationException("新增地址失败");
        }
    }

    /**
     * 地址薄分页查询
     * @param dto
     * @return
     */
    @Override
    public PageResult<AddressBook> pageQuery(AddressBookPageQueryReqDTO dto) {
        Long userId = UserContext.currentUserId();
        if (ObjectUtil.isNull(userId)) {
            throw new ForbiddenOperationException("请登录后再操作");
        }
        return PageHelperUtils.selectPage(dto,
                () -> this.lambdaQuery().eq(AddressBook::getUserId, userId).list()
        );
    }

    /**
     * 修改地址
     * @param id
     * @param dto
     */
    @Override
    public void updateAddressBook(Long id, AddressBookUpsertReqDTO dto) {
        Long userId = UserContext.currentUserId();
        if (ObjectUtil.isNull(userId)) {
            throw new ForbiddenOperationException("请登录后再操作");
        }

        // 默认地址一个人只有一个，如果设置新地址为默认地址需要取消旧的默认地址
        if (dto.getIsDefault() == 1) {
            this.lambdaUpdate()
                    .set(AddressBook::getIsDefault, 0)
                    .eq(AddressBook::getUserId, userId)
                    .eq(AddressBook::getIsDefault, 1)
                    .update();
        }
        AddressBook addressBook = BeanUtil.copyProperties(dto, AddressBook.class);
        addressBook.setUserId(userId);
        addressBook.setId(id);
        // 获取经纬度
        String location = mapApi.getLocationByAddress(dto.getAddress()).getLocation();
        addressBook.setLon(NumberUtils.parseDouble(location.split(",")[0]));
        addressBook.setLat(NumberUtils.parseDouble(location.split(",")[1]));
        boolean flag = this.updateById(addressBook);
        if (!flag) {
            throw new ForbiddenOperationException("修改地址失败");
        }
    }

    /**
     * 批量删除地址
     * @param ids
     */
    @Override
    public void batchDelete(List<Long> ids) {
        boolean flag = this.removeByIds(ids);
        if (!flag) {
            throw new ForbiddenOperationException("删除地址失败");
        }
    }

    /**
     * 设置默认地址
     * @param flag
     * @param id
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void setIsDefault(Integer flag, Long id) {
        Long userId = UserContext.currentUserId();
        if (ObjectUtil.isNull(userId)) {
            throw new ForbiddenOperationException("请登录后再操作");
        }
        
        // 获取用户地址的数量
        Integer count = this.lambdaQuery().eq(AddressBook::getUserId, userId).count();

        // 如果用户地址数量为1，则不允许取消默认地址
        if (count == 1) {
            throw new ForbiddenOperationException("地址数量为1，不允许取消默认地址");
        }
        
        // 如果设置新地址为默认地址需要取消旧的默认地址
        if (flag == 1) {
            boolean update = this.lambdaUpdate()
                    .set(AddressBook::getIsDefault, 0)
                    .eq(AddressBook::getUserId, userId)
                    .eq(AddressBook::getIsDefault, 1)
                    .update();
            if (!update) {
                throw new ForbiddenOperationException("设置默认地址失败");
            }

        }
        boolean update = this.lambdaUpdate().set(AddressBook::getIsDefault, flag)
                .eq(AddressBook::getId, id)
                .update();
        if (!update) {
            throw new ForbiddenOperationException("设置默认地址失败");
        }
    }

    /**
     * 获取默认地址
     *
     * @return
     */
    @Override
    public AddressBook getDefaultAddress() {
        Long userId = UserContext.currentUserId();
        if (ObjectUtil.isNull(userId)) {
            throw new ForbiddenOperationException("请登录后再操作");
        }
        return this.lambdaQuery()
                .eq(AddressBook::getUserId, userId)
                .eq(AddressBook::getIsDefault, 1)
                .one();
    }
}
